package com.example.hasee.test;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.hasee.test.fragment.fourFragment;
import com.example.hasee.test.fragment.oneFragment;
import com.example.hasee.test.fragment.threeFragment;
import com.example.hasee.test.fragment.twoFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener {

    private List<Fragment> list;
    private FragmentManager fm;
    private RadioGroup rg;
    private int count=0;
    private RadioButton[] radiobuttons;

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = new ArrayList<>();
        fm =getSupportFragmentManager();
        rg =  this.findViewById(R.id.rg);
        radiobuttons = new RadioButton[rg.getChildCount()];
        for (int i = 0; i < radiobuttons.length; i++) {
            radiobuttons[i] = (RadioButton) rg.getChildAt(i);

        }
        list.add(new oneFragment());
        list.add(new twoFragment());
        list.add(new threeFragment());
        list.add(new fourFragment());

        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.layout,list.get(0));
        ft.commit();
        rg.setOnCheckedChangeListener(this);


        //提交测试
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int id) {
        switch (id){
            case R.id.rb1:
                shows(R.id.rb1);
                break;
            case R.id.rb2:
                shows(R.id.rb2);
                break;
            case R.id.rb3:
                shows(R.id.rb3);
                break;
            case R.id.rb4:
                shows(R.id.rb4);
                break;
        }
    }

    private void shows(int rb1) {
        FragmentTransaction ft = fm.beginTransaction();
        for (int i = 0; i <radiobuttons.length ; i++) {
            if(rb1==radiobuttons[i].getId()){

                if(list.get(i).isAdded()){
                    ft.show(list.get(i)).hide(list.get(count)).commit();
                }else {
                    ft.add(R.id.layout,list.get(i)).hide(list.get(count)).commit();
                }
                count = i;
                break;
            }

        }

    }
}
